package com.gome.extract;
import java.io.IOException;  
import java.io.OutputStream;
import java.io.PrintWriter;  
import java.util.Date;  
  

import java.util.HashMap;

import javax.servlet.AsyncContext;  
import javax.servlet.AsyncEvent;  
import javax.servlet.AsyncListener;  
import javax.servlet.ServletException;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import org.apache.log4j.Logger;

import com.gome.extract.common.AppConfiguer;
  
  
/** 
 * servlet3.0默认是不支持异步的通过asyncSupported=true,打开 
 *  
 */
public class TestThread extends HttpServlet 
{
	private static Logger logger = Logger.getLogger(TestThread.class);
	private  HashMap<String, MyThread> mRequestManger = new HashMap<String, MyThread>();
	public synchronized boolean isExist(HttpServletRequest request)
	{
		String query = request.getQueryString();
		String type = request.getParameter("type");
		if(type.equals("test"))
			return false;
		
		logger.info("Get request : " + query);
		if(mRequestManger.containsKey(query))
		{
			if (mRequestManger.get(query).isEnd()) {
				mRequestManger.remove(query);
				return false;
			}
			return true;
		}
		return false;
	}
	
	public synchronized void addExist(HttpServletRequest request, MyThread thread)
	{
		String query = request.getQueryString();
		String type = request.getParameter("type");
		if(type.equals("test"))
			return ;

		mRequestManger.put(query, thread);

	}
	
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	{
        resp.setContentType("text/html; charset=utf-8");  
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
    	resp.setHeader("Content-type", "text/html;charset=UTF-8");
        try 
		{
       	 
        	if(isExist(req))
    		{
        		PrintWriter out  = resp.getWriter(); 
        		out.print("0");
        		out.flush();  
        		out.close();
        		return;
    		}
        	
            AsyncContext asyncContext = req.startAsync();  
            
            /** 
             * AsyncListener为什么没有适配器呢？需要各个厂家实现？ 
             */  
            asyncContext.addListener(new AsyncListener()
			{
            	@Override
                public void onComplete(AsyncEvent asyncEvent) throws IOException 
				{  
                    //将流在这里关闭  
                    asyncEvent.getSuppliedResponse().getWriter().close();  
                    logger.info("Finished .");
                }

				@Override
				public void onError(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onStartAsync(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onTimeout(AsyncEvent arg0) throws IOException {
					// TODO Auto-generated method stub
					
				}
            });
            
            MyThread mythread = new MyThread(asyncContext, req);
            addExist(req, mythread);
            
            Thread thread = new Thread(mythread);
            thread.start();

            return;
        }
        catch(Exception e)
        {
        	logger.error(AppConfiguer.getTrace(e));
        }
    }  
}